<?php

class ThemeFolderFixer
{
	var $db_info = null;
	var $db_link = null;
	
	/**
	 *
	 */
	function __construct($db_info)
	{
		if (empty($db_info))
		{
			exit("[ThemeFolderFixer] error: missing one or more required parameters\n");
		}
		
		$this->db_info = $db_info;
				
		$this->db_link = mysql_connect($db_info['hostname'], $db_info['username'], $db_info['password'])
			or die('[ThemeFolderFixer] error: could not connect to server: ' . mysql_error());
			
		mysql_select_db($db_info['database']) 
			or die('[ThemeFolderFixer] error: could select datbase: ' . mysql_error());
	}
	
	/**
	 *
	 */
	function fix($find,$replace_with)
	{		
		$replace_with_length=strlen($replace_with);
		$offset=strlen($find)+2;
		$site_system_preferences_rows = $this->get_site_system_preferences();
		
		foreach ($site_system_preferences_rows as $row)
		{
			$site_system_preferences = $row['site_system_preferences'];
			$site_id = $row['site_id'];
			print('site ' .$site_id.' BEFORE: ' . $site_system_preferences);
			$find_pos=strpos($site_system_preferences,$find);
			$end_pos=strpos($site_system_preferences,";",$find_pos+$offset);
			$left=substr($site_system_preferences,0,$find_pos+$offset);
			$right=substr($site_system_preferences,$end_pos);
			$new_site_system_preferences = $left . "s:" .$replace_with_length. ':"'. $replace_with . '"' . $right;
			$query = "UPDATE exp_sites SET site_system_preferences = '$new_site_system_preferences' WHERE site_id = '$site_id'";
			print('site ' .$site_id.' AFTER: ' . $new_site_system_preferences);
			$this->execute_query($query);
		}
	}
		
	/**
	 *
	 */
	function get_site_system_preferences()
	{
		$site_system_preferences = '';
		$query = "SELECT site_system_preferences, site_id FROM exp_sites";
		$rows = $this->get_query_rows($query);
		return $rows;
	}
		
	/**
	 *
	 */
	function get_query_rows($query)
	{
		$rows = array();
		$result = mysql_query($query, $this->db_link) 
			or die('[ThemeFolderFixer] error: Query failed: ' . mysql_error());
		if (mysql_num_rows($result) > 0)
		{
			while (($row = mysql_fetch_assoc($result)))
			{
				$rows[] = $row;
			}
		}
		return $rows;
	}
	
	/**
	 *
	 */
	function execute_query($query)
	{
		$result = mysql_query($query, $this->db_link) 
			or die('[ThemeFolderFixer] error: Query failed: ' . mysql_error());		
		$affected = mysql_affected_rows($this->db_link);
		return $affected;
	}
}


?>